/**
 * 生成随机验证码
 * @returns {string} 验证码字符串
 */
export function generateCaptchaCode() {
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  let captcha = '';
  for (let i = 0; i < 4; i++) {
    captcha += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return captcha;
}

/**
 * 生成验证码图片
 * @param {string} code 验证码字符串
 * @returns {string} 验证码图片的base64数据
 */
export function generateCaptchaImage(code) {
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');
  canvas.width = 120;
  canvas.height = 40;
  
  // 绘制背景
  ctx.fillStyle = '#f0f0f0';
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  
  // 绘制干扰线
  for (let i = 0; i < 5; i++) {
    ctx.strokeStyle = `rgb(${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)})`;
    ctx.beginPath();
    ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
    ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
    ctx.stroke();
  }
  
  // 绘制验证码
  ctx.font = '20px Arial';
  ctx.fillStyle = '#000';
  for (let i = 0; i < code.length; i++) {
    ctx.save();
    ctx.translate(20 + i * 20, 20 + Math.random() * 10);
    ctx.rotate(Math.random() * 0.4 - 0.2);
    ctx.fillText(code[i], 0, 0);
    ctx.restore();
  }
  
  return canvas.toDataURL();
}

/**
 * 生成新的验证码URL
 * @returns {object} 包含验证码图片和验证码字符串的对象
 */
export function generateCaptcha() {
  const code = generateCaptchaCode();
  const imageUrl = generateCaptchaImage(code);
  return { imageUrl, code };
}

/**
 * 刷新验证码
 * @param {Function} setCaptchaData 设置验证码数据的函数
 */
export function refreshCaptcha(setCaptchaData) {
  const captchaData = generateCaptcha();
  setCaptchaData(captchaData);
}